'use strict';

const Controller = require('egg').Controller;

class BaseController extends Controller {

	/**
     * 像多个用户发送消息
     *
     * @param {Array}  sendess -接收者用户名 username
     * @param {String} content -消息内容
     * @param {String} title -消息标题
     * @param {Number} type -消息类型
     * @param {Boolean} removeOneself -去除接收者中的自己
     */

	async submitMsg({ sendees = [], title, content, type, removeOneself = true }) {
		const { ctx } = this;
		const loginuser = ctx.state.user.username;
		const loginuser_index = sendees.indexOf(loginuser);
		if (removeOneself && sendees.includes(loginuser)) {
			sendees.splice(loginuser_index, 1);
			console.log(`去除被@用户中的自己`);
		}
		for (let sendee of sendees) {
			try {
				await ctx.service.message.create({
					content,
					title,
					type,
					username: sendee
				});
				console.log(`向${sendee}发送消息成功`);
			} catch (e) {
				console.log(`向${sendee}发送消息失败`, e);
			}
		}
	}

	/**
     * 像多个用户ID发送消息
     *
     * @param {Array}  sendess -接收者用户ID
     * @param {String} content -消息内容
     * @param {String} title -消息标题
     * @param {Number} type -消息类型
     * @param {Boolean} removeOneself -去除接收者中的自己
     */

	async submitMsg({ sendees = [], title, content, type, removeOneself = true }) {
		const { ctx } = this;
		const loginuser = ctx.state.user._id;
		const loginuser_index = sendees.indexOf(loginuser);
		if (removeOneself && sendees.includes(loginuser)) {
			sendees.splice(loginuser_index, 1);
			console.log(`去除被@用户中的自己`);
		}
		for (let sendee of sendees) {
			try {
				await ctx.service.message.create({
					content,
					title,
					type,
					username: sendee
				});
				console.log(`向${sendee}发送消息成功`);
			} catch (e) {
				console.log(`向${sendee}发送消息失败`, e);
			}
		}
	}
}

module.exports = BaseController;
